const app = getApp()
var netUtil = require("../../utils/netUtil.js"); //require引入
var page = 1;
Page({
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '订单管理', //导航栏 中间的标题
    },
    height: app.globalData.height * 2 + 20,
    orderState: ["待付款", "分期中","已逾期", "已完成"],
    currentTab: 0,
    data: {
      refreshing: false, // 将refreshing设为true，可支持自动触发下拉刷新的场景。同样会触发refresh事件
      refreshed: false, // 将本属性设置为true，收起下拉刷新，可多次设置为true（即便原来已经是true了）
    },
    flag: true,//支付方式
    list:[],
    userInfo:'',
    isEwm: true,
    token:'',
    payWayList:[],
    isShow:false,
    payWayTab:0,
    totalPrice:0,
    first_price:'',
    school_class_id:'',
    order_pay_id:'',
    couponName:'',
    coupon_id:'',
    is_coupon:null,//是否可使用优惠券

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    this.setData({
      currentTab: options.type,
    })
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let pages = getCurrentPages();
      let currPage = pages[pages.length - 1];
      if(currPage.data.couponId){
        this.setData({
          coupon_id:currPage.data.couponId,
          couponName:currPage.data.couponName
        })
        if(this.data.first_price){
          const params={
            school_pay_many_id:this.data.payWayList[this.data.payWayTab].id,
            school_class_id:this.data.school_class_id,
            first_price:this.data.first_price,
            token:this.data.token,
            coupon_id:this.data.coupon_id
          }
          netUtil.postData('order-pay/getPayManyPrice',params, (datas) => {
            if(datas.code===1){
              this.setData({
                pay_many_price:datas.data.pay_many_price,
                totalPrice:datas.data.total_price
              })
            }else{
              wx.showToast({
                title: datas.msg,
                icon:'none'
              })
            }  
          })
        }

      }else{
        this.setData({
          userInfo: wx.getStorageSync("userInfo"),
          list: [],
          token:wx.getStorageSync("token")
        })
        page = 1
        this.getList(page)
      }
    
  },
    // 选择优惠券
    toCoupon(){
     if(this.data.is_coupon==0){
        wx.showToast({
          title: '暂无可用优惠券',
          icon:'none'
        })
      }else{
        wx.navigateTo({
          url: '/pages/coupon/coupon?isSelect=true',
        })
      }
    },
  // 上拉刷新
  refresh() {
    // 这是做网络请求的时机
    const that = this
    wx.showToast({
      title: '请稍等',
      icon: 'none',
      complete() {
        that.setData({
          list: []
        })
        page = 1
        that.getList(page)
      }
    });
  },
  onReachBottom: function () {
    var that = this;
    // 显示加载图标
    wx.showLoading({
      title: '玩命加载中',
    })
    // 页数+1
    page = page + 1;
    this.getList(page)
  },
  // 报名成功  选择付款方式
  selectPay(e){
    const params={
      school_class_id:e.currentTarget.dataset.id,
      token: this.data.token,    
    }
    netUtil.postData('school-pay-many/listEnrollAll', params, (datas) => {
      if (datas.code==1){
        this.setData({
          is_coupon:datas.data.is_coupon,
          order_pay_id:e.currentTarget.dataset.orderid,
          school_class_id:e.currentTarget.dataset.id,
          payWayList:datas.data.lists,
          isShow:true,
          totalPrice:datas.data.lists[this.data.payWayTab].price
        })
      }else{
        wx.showToast({
          title: datas.msg,
          icon:'none'
        })
      }
    })
  },
  getPayments(e){
    this.setData({
     first_price:e.detail.value
    })
    const params={
      school_pay_many_id:this.data.payWayList[this.data.payWayTab].id,
      school_class_id:this.data.school_class_id,
      first_price:this.data.first_price,
      token:this.data.token,
      coupon_id:this.data.coupon_id
    }
    netUtil.postData('order-pay/getPayManyPrice',params, (datas) => {
      if(datas.code===1){
        this.setData({
          pay_many_price:datas.data.pay_many_price,
          totalPrice:datas.data.total_price
        })
      }else{
        wx.showToast({
          title: datas.msg,
          icon:'none'
        })
      }  
    })
  },
  // 选择付款方式
payWayChange(e){
  this.setData({
    payWayTab:e.currentTarget.dataset.current,
    totalPrice:this.data.payWayList[0].price,
    school_pay_many_id:this.data.payWayList[e.currentTarget.dataset.current].id
  })
  if(this.data.school_pay_many_id!=0){
    const params={
      school_pay_many_id:this.data.payWayList[this.data.payWayTab].id,
      school_class_id:this.data.school_class_id,
      first_price:this.data.first_price,
      token:this.data.token
    }
    netUtil.postData('order-pay/getPayManyPrice',params, (datas) => {
      if(datas.code===1){
        this.setData({
          pay_many_price:datas.data.pay_many_price,
          totalPrice:datas.data.total_price
        })
      }else{
        wx.showToast({
          title: datas.msg,
          icon:'none'
        })
      }  
    })
  }
},
isShowHide(){
  this.setData({
    isShow:false
  })
},
submitTap(){
  const params={
    school_pay_many_id:this.data.payWayList[this.data.payWayTab].id,
    order_pay_id:this.data.order_pay_id,
    token:this.data.token,
    first_price:this.data.first_price,
    coupon_id:this.data.coupon_id
  }
  netUtil.postData('order-pay/enrollPayMany',params, (datas) => {
    if(datas.code===1){
      this.payoff(datas.data.order_number,datas.data.order_pay_id)
    }else{
      wx.showToast({
        title: datas.msg,
        icon:'none'
      })
    }  
  })
},
  // 发起支付
  payoff(order_number,order_pay_id){
    const that=this
    const params={
      order_number:order_number,
      token:that.data.token
    }
    netUtil.postData('order/pay',params, (datas) => {
      if(datas.code===1){
        wx.requestPayment({
          timeStamp: datas.data.timeStamp,
          nonceStr: datas.data.nonceStr,
          package: datas.data.package,
          signType: datas.data.signType,
          paySign: datas.data.paySign,
          success(res) { 
            wx.showToast({
              title: '支付成功',
            })
            that.setData({
              list: [],
              isShow:false
            })
            page = 1
            that.getList(page)
          },
          fail(res) { 
            console.log(res)
          }
        })
      }else{
        wx.showToast({
          title: datas.msg,
          icon:'none'
        })
      }
    })
  },
  // 获取列表
  getList(page) {
    let params = {
      page: page,
      status: this.data.currentTab*1+1,
      token: this.data.token
    }
    netUtil.postData('order-pay/list', params, (datas) => {
      if (datas.code==1){
        const oldData = this.data.list;
        this.setData({
          list: oldData.concat(datas.data.lists),
          refreshed: true,
        })
        wx.hideLoading();
      }else{
        wx.showToast({
          title: datas.msg,
          icon:'none'
        })
      }
      
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  payTap(e) {
    const that=this
    const params={
      order_number:e.currentTarget.dataset.order,
      token: that.data.token,
    }
    netUtil.postData('order/pay', params, (datas) => {
      if (datas.code==1){
        wx.requestPayment({
          timeStamp: datas.data.timeStamp,
          nonceStr: datas.data.nonceStr,
          package: datas.data.package,
          signType: datas.data.signType,
          paySign: datas.data.paySign,
          success(res) { 
            wx.showToast({
              title: '支付成功',
            })
            that.setData({
              list: []
            })
            page = 1
            that.getList(page)
          },
          fail(res) { 
            console.log(res)
          }
        })
      }else{
        wx.showToast({
          title: datas.msg,
          icon:'none'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  //规格点击切换
  stateTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current,
        list: []
      })   
      page = 1
      that.getList(page)
    }

  },
  // 隐藏支付方式
  isHide() {
    this.setData({
      flag: true
    })
  },
  // 订单详情
  detail(e){
    wx.navigateTo({
      url: '/pages/billDetail/billDetail?id=' + e.currentTarget.id,
    })
  },

  // 保存二维码
  gotoSaveImg() {
    var that = this;
    wx.downloadFile({
      url: that.data.ewmImg,
      success: function (res) {
        console.log(res);
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function (err) {

          },
          complete(res) {
            console.log(res);
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '铅笔教育',
      desc: '',
      path: 'pages/index/index?union_user_id=' + wx.getStorageSync("userInfo").id
    }
  }
})